﻿using Red.Core.Network.PacketNetwork;
using System.IO;

namespace Red.CommUtils.TcpMessageProtocol
{
    public class ChannelResponse : IResponse
    {
        private PacketNetworkManager _network;
        private int _connectionID;
        private ushort _handle;
        private MessageFlags _flags;

        public ChannelResponse( int connectionID, PacketNetworkManager network, ushort handle, MessageFlags flags )
        {
            _network = network;
            _connectionID = connectionID;
            _handle = handle;
            _flags = flags;
        }

        public void Send( comm.Message response )
        {
            MemoryStream data = new MemoryStream();
            ProtoWriterBinary writer = new ProtoWriterBinary( data );

            writer.WriteUint8( (byte)_flags );
            if ( _flags.HasFlag( MessageFlags.Ack ) || _flags.HasFlag( MessageFlags.NeedsAck ) )
            {
                writer.WriteUint16( _handle );
            }

            response.Serialize( writer );
            _network.Send( _connectionID, data );
        }
    }

    public class TcpResponseFactory : IResponseFactory
    {
        private int _connectionID;
        private PacketNetworkManager _network;

        public TcpResponseFactory( int connectionID, PacketNetworkManager network )
        {
            _connectionID = connectionID;
            _network = network;
        }

        public IResponse Create( MessageFlags flags = MessageFlags.FireAndForget, ushort handle = 0 )
        {
            return new ChannelResponse( _connectionID, _network, handle, flags );
        }
    }
}
